/**
 * 版权所有：厦门雅迅网络股份有限公司
 * Copyright (C) 2012 Xiamen Yaxon Networks CO.,LTD.
 * All right reserved.
 *====================================================
 * 文件名称: Bootstrap
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2012-04-18			zhangwz(创建:创建文件)
 *====================================================
 */
package com.tcp2.server;


import com.tcp2.net.MasterLink;
import com.tcp2.ui.MainFrame;
import com.yaxon.vndp.common.util.Bootstrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.swing.*;

/**
 * 企业平台接入服务器
 */
public class DataExchangeServer extends Bootstrap {
    private static Logger logger = LoggerFactory.getLogger(DataExchangeServer.class);

    public static final String APP_NAME  = "app.name";
    public static final String SPRING_CONFIG = "spring.config";
    public static final String DEFAULT_SPRING_CONFIG = "classpath*:META-INF/spring/*.xml";

    private ApplicationContext appContext;
    private MasterLink masterLink;

    public static void main(String[] args) {
        try {
            DataExchangeServer app = new DataExchangeServer();
            app.run(args);//
        } catch (Throwable e) {
            logger.error("", e);
            System.exit(3);
        }
    }


    @Override
    public String appName() {
        return System.getProperty(APP_NAME);
    }

    public void setup() throws Exception {
        String configPath = System.getProperty(SPRING_CONFIG);
        if (configPath == null || "".equals(configPath.trim())) {
            configPath = DEFAULT_SPRING_CONFIG;
        }
        try {
            appContext = new ClassPathXmlApplicationContext(configPath.split("[,\\s]+"));

            MessageDispatcher messageDispatcher = appContext.getBean(MessageDispatcher.class);
            messageDispatcher.init(appContext);

            masterLink = appContext.getBean(MasterLink.class);
            if (masterLink == null) {
                throw new Exception("获取 MasterLink 实例失败!");
            }

        } catch (Exception e) {
            throw new Exception("程序初始化失败", e);
        }
    }

    public void start() throws Exception {
        try {
            masterLink.start();
            MainFrame mf= new MainFrame();
        } catch (Exception e) {
            throw new Exception("程序启动失败", e);
        }
    }

    public void stop() throws Exception {
        try {

            if (masterLink != null) {
                masterLink.stop();
                masterLink = null;
            }
        } catch (Throwable e) {
            throw new Exception("程序关闭失败", e);
        }
    }
}
